package com.chenjim.daemon.model;

import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.text.TextUtils;

import com.chenjim.daemon.service.LocalFrondService;
import com.chenjim.daemon.service.RemoteService;

import java.util.List;

/**
 * @description：
 * @fileName: DualProgressManager
 * @author: jim.chen
 * @date: 2020/4/7
 */
public class DaemonManager {

    public static void daemon(Context context) {
        //判断服务是否在运行
        boolean isLocalServiceRun = isServiceRunning(context, LocalFrondService.class.getName());
        boolean isRemoteServiceRun = isServiceRunning(context, RemoteService.class.getName());
        if (!isLocalServiceRun || !isRemoteServiceRun) {

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                //https://blog.csdn.net/wolinxuebin/article/details/87206390
                //fix Not allowed to start service Intent app is in background
                context.startForegroundService(new Intent(context, LocalFrondService.class));
                context.startForegroundService(new Intent(context, RemoteService.class));

            } else {
                context.startService(new Intent(context, LocalFrondService.class));
                context.startService(new Intent(context, RemoteService.class));
            }
        }

    }

    public static boolean isServiceRunning(Context context, String serviceName) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> runningServices = am.getRunningServices(10);
        for (ActivityManager.RunningServiceInfo runningService : runningServices) {
            if (TextUtils.equals(runningService.service.getClassName(), serviceName)) {
                return true;
            }
        }
        return false;
    }
}
